package com.atguigu.gmall.activity.listener;

import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import com.atguigu.gmall.activity.utils.DateUtil;
import com.atguigu.gmall.common.constans.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;


@Component
public class SeckillGoodsListener {


    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    //接收消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TASK_1,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_TASK),
            key = {MqConst.ROUTING_TASK_1}
    ))
    public void receiverResult(Message message, Channel channel)  {
        try {
              //0:查询DB的数据
            /**
             * # 数据是当天的  商品的数据必须有货、必须是审核通过的
             * select * from seckill_goods
             * where `status` = 1 and stock_count > 0 and
             * DATE_FORMAT(start_time,'%Y-%m-%d') = '2022-02-09'
             *
             */
            QueryWrapper<SeckillGoods> queryWrapper = new QueryWrapper<>();
            //商品的数据必须有货
            queryWrapper.gt("stock_count" , "0")
                    //必须是审核通过的
                    .eq("status", 1)
                    //数据是当天的
                    .eq("DATE_FORMAT(start_time,'%Y-%m-%d')" , DateUtil.formatDate(new Date()));
            //查询数据
            List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectList(queryWrapper);


            //Redis: hash散列类型
            if (!CollectionUtils.isEmpty(seckillGoodsList)){
                for (SeckillGoods seckillGoods : seckillGoodsList) {
                    //1 判断是否已经同步完成
                    if (!redisTemplate.opsForHash().hasKey(RedisConst.SECKILL_GOODS,
                            seckillGoods.getSkuId().toString())){

                        //2:未完成 将DB数据库中数据 同步到redis中
                        // 保存秒杀商品到redis缓存中
                        redisTemplate.opsForHash().put(RedisConst.SECKILL_GOODS,
                                seckillGoods.getSkuId().toString(),seckillGoods);

                        // //提前将要秒杀的相应数量的商品本身直接保存到缓存的List类型中  防止商品超卖
                        redisTemplate.opsForList().leftPush(RedisConst.SECKILL_STOCK_PREFIX+seckillGoods.getSkuId(),
                                buildSeckillGoodsData(seckillGoods));// 30 push 10次
                        //状态位 群发

                    }else {
                        //3.如果已经完成 , 不同步了
                        System.out.println("已完成 , 不在同步");
                    }
                }
            }
            //应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String[] buildSeckillGoodsData(SeckillGoods seckillGoods) {
        String[] skuIds = new String[seckillGoods.getStockCount()];
        for (Integer i = 0; i < seckillGoods.getStockCount(); i++) {
            skuIds[i]  = seckillGoods.getSkuId().toString();
        }
        return skuIds;
    }
}
